package developer.算法.矩阵.螺旋矩阵;

import java.util.ArrayList;
import java.util.List;

/**
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * <p>
 * [1,2,3]
 * [4,5,6]
 * [7,8,9]
 * <p>
 * [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 */
public class LuoXuanJvZhen {
    public static void main(String[] args) {

        spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}).forEach(System.out::println);
        System.out.println("----------");
        spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}).forEach(System.out::println);
    }

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>(matrix.length * matrix[0].length);
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
        for (; ; ) {
            //从左到右
            for (int i = left; i <= right; i++) {
                int val = matrix[top][i];
                result.add(val);
            }
            top += 1;
            if (top > bottom) {
                break;
            }

            //从上到下
            for (int i = top; i <= bottom; i++) {
                int val = matrix[i][right];
                result.add(val);
            }
            right -= 1;

            if (right < left) {
                break;
            }

            //从右往左
            for (int i = right; i >= left; i--) {
                int val = matrix[bottom][i];
                result.add(val);
            }
            bottom -= 1;
            if (bottom < top) {
                break;
            }

            //从下往上
            for (int i = bottom; i >= top; i--) {
                int val = matrix[i][left];
                result.add(val);
            }
            left += 1;
            if (left > right) {
                break;
            }

        }
        return result;

    }


}
